package com.example.wsnapi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.widget.Toast;

public class PreferencesActivity extends Activity {


	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.preferences_layout);

		getFragmentManager().beginTransaction().replace(R.id.fragment_container, new UserPreferencesFragment()).commit();

	}

	public static class UserPreferencesFragment extends PreferenceFragment{
		Preference mCostamPreference;
		Preference ipAddressPreference;
		SharedPreferences sharedPref ;
		private OnSharedPreferenceChangeListener mListener;
		OnPreferenceChangeListener mChangeListener;
		@Override
		public void onCreate(Bundle savedInstanceState){
			super.onCreate(savedInstanceState);

			addPreferencesFromResource(R.xml.preferences);
			
			mCostamPreference = (Preference)getPreferenceManager().findPreference("database");
			ipAddressPreference = findPreference("ip_address");
			mChangeListener = new OnPreferenceChangeListener(){
				
				private static final String PATTERN = 
				        "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
				        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
				        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
				        "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
				@Override
				public boolean onPreferenceChange(Preference pref, Object newVal)
				{
					
					Pattern pattern = Pattern.compile(PATTERN);
				      Matcher matcher = pattern.matcher((CharSequence)newVal);
				     
					if( !matcher.matches() )
					{
						Toast.makeText(getActivity().getApplicationContext(), "IP Address is invalid", Toast.LENGTH_SHORT).show();
						return false;
					}
					return true;
					
				}
			};
			mListener = new OnSharedPreferenceChangeListener(){
				@Override
				public void onSharedPreferenceChanged(
						SharedPreferences sharedPreferences, String key)
				{
					mCostamPreference.setSummary(sharedPreferences.getString("database", "Not set"));
					ipAddressPreference.setSummary(sharedPreferences.getString("ip_address", "enter ip address"));
					
				}
				
			};
			sharedPref= getPreferenceScreen().getSharedPreferences();
			sharedPref.registerOnSharedPreferenceChangeListener(mListener);
			ipAddressPreference.setOnPreferenceChangeListener(mChangeListener);
			mListener.onSharedPreferenceChanged(sharedPref, "database");
		}
		
	}
}
